package com.zbkj.service.dividend.listener;

import com.zbkj.service.dividend.event.DividendEvent;
import com.zbkj.service.dividend.event.DividendPoolEvent;
import com.zbkj.service.dividend.service.DividendPoolChangeService;
import com.zbkj.service.dividend.service.DividendPoolService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

/**
 * 用户分红池更新监听器
 */
@Component
public class DividendPoolListener {

    @Autowired
    DividendPoolChangeService dividendPoolChangeService;

    @Autowired
    DividendPoolService dividendPoolService;

    private static final Logger log = LoggerFactory.getLogger(DividendPoolListener.class);

    /**
     * 处理用户分红池更新事件
     */
    @EventListener
    public void handleUserDividendUpdate(DividendPoolEvent event) {
        try {
            log.info("处理用户分红池更新: {}", event.getChangeDescription());
            dividendPoolChangeService.updateUserDividendPool(event.getUserId());
            log.info("用户分红池更新处理完成: 用户[{}]", event.getUserId());
        } catch (Exception e) {
            log.error("处理用户分红池更新异常: {}", event.getChangeDescription(), e);
        }
    }

    /**
     * 处理用户分红池分红事件
     */
    @EventListener
    public void handleUserDividend(DividendEvent event) {
        String orderNo = event.getOrder().getOrderNo();
        try {
            log.info("处理用户分红: {}", orderNo);
            dividendPoolService.executeOrderDividend(event.getOrder());
            log.info("用户分红处理完成: 订单号[{}]", orderNo);
        } catch (Exception e) {
            log.error("处理用户分红异常，订单号: {}", orderNo, e);
        }
    }
}